#!/usr/bin/python3
# -*- coding: utf-8 -*-

from PyQt5.QtCore import Qt, QPoint, QSize
from PyQt5.QtGui import QPixmap, QPainter, QPen, QColor
from PyQt5.QtWidgets import QWidget


class DrawPanel(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        # 初始化参数
        self.panel_size = QSize(240, 240)  # 画板尺寸
        self.board_color = QColor(255, 255, 255, 255)  # 画板颜色

        self.pen_color = QColor(0, 0, 0, 255)  # 画笔颜色
        self.thickness = 15  # 画笔粗细

        self.begin_point = QPoint()
        self.end_point = QPoint()

        # 画笔
        self.draw_painter = QPainter()

        # 画板
        self.draw_panel = QPixmap(self.panel_size)
        self.draw_panel.fill(self.board_color)
        self.setFixedSize(self.panel_size)

    # 清空画板
    def clear_draw_panel(self):
        self.draw_panel.fill(self.board_color)
        self.update()

    # 获取画板QImage类型图片
    def get_draw_panel_image(self):
        return self.draw_panel.toImage()

    # 双缓冲绘图，绘图事件
    def paintEvent(self, paintEvent):
        self.draw_painter.begin(self)
        self.draw_painter.drawPixmap(0, 0, self.draw_panel)
        self.draw_painter.end()

    def mousePressEvent(self, mouseEvent):
        if mouseEvent.button() == Qt.LeftButton:
            self.begin_point = mouseEvent.pos()

    def mouseMoveEvent(self, mouseEvent):
        if mouseEvent.buttons() == Qt.LeftButton:
            self.end_point = mouseEvent.pos()

            self.draw_painter.begin(self.draw_panel)
            self.draw_painter.setPen(QPen(self.pen_color, self.thickness))
            self.draw_painter.drawLine(self.begin_point, self.end_point)
            self.draw_painter.end()
            # 更新起点为上一次绘制的终点
            self.begin_point = self.end_point
            self.update()
